package com.yingside.jdbc.crm;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestMoney {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        int n = 0;

        try {
            conn = DBHelper.getConn();
            //设置不需要自动提交
            conn.setAutoCommit(false);

            String sql1 = "update t_bank set money = money - 100 where name=?";
            ps = conn.prepareStatement(sql1);
            ps.setString(1,"张三");

            n = ps.executeUpdate();

            if(n > 0){
                String sql2 = "update t_bank set mone = money + 100 where name=?";
                ps = conn.prepareStatement(sql2);
                ps.setString(1,"李四");

                n = ps.executeUpdate();

                if(n > 0 ){
                    System.out.println("执行成功");
                    //执行成功之后提交
                    conn.commit();
                }
                else{
                    System.out.println("执行失败");
                }
            }
            else{
                System.out.println("执行失败");
            }
        } catch (SQLException e) {
            try {
                //如果出现异常，回滚整个事务
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                //将自动提交设置为true
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            DBHelper.close(null,ps,conn);
        }
    }
}
